package com.appkubes.mall.admin.application.promoter.statis.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.cloud.config.params.paramValid.ParamValid;
import com.appkubes.common.Response;
import com.appkubes.common.constants.BaseConstants;
import com.appkubes.common.utils.net.HttpClientUtils;
import com.appkubes.mall.admin.application.order.order.service.OrderService;
import com.appkubes.mall.admin.application.plugin.rent.service.PluginRentUrlService;
import com.appkubes.mall.admin.application.promoter.statis.dao.PromoterStatisDao;
import com.appkubes.mall.admin.application.promoter.statis.entity.dto.PromoterStatisDTO;
import com.appkubes.mall.admin.application.promoter.statis.entity.vo.PromoterStatisSearchVO;
import com.appkubes.mall.core.entity.MallOrder;
import com.appkubes.mall.core.entity.MallOrderGoods;
import com.appkubes.mall.core.service.BaseMallOrderGoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/promoter/statis")
@Api(tags = "推广员统计模块")
@Slf4j
public class PromoterStatisController {
    @Resource
    PromoterStatisDao promoterStatisDao;

    @Resource
    PluginRentUrlService pluginRentUrlService;

    @Resource
    OrderService orderService;

    @Resource
    BaseMallOrderGoodsService baseMallOrderGoodsService;

    @ApiOperation("获取统计信息")
    @GetMapping("/get")
    public Response getStatis(@ParamValid PromoterStatisSearchVO statisSearchVO) {
        Page<PromoterStatisDTO> page = new Page<>(statisSearchVO.getPage(), statisSearchVO.getSize());
        IPage<PromoterStatisDTO> statisDTO = promoterStatisDao.selectPromoterStatis(page, statisSearchVO.getPromoterKey());
        List<PromoterStatisDTO> records = statisDTO.getRecords();
        for (PromoterStatisDTO promoter:records) {
            promoter.setUserStatu(getUserStatu(promoter.getUserKey()));

            // 尝试获取最新订单
            QueryWrapper<MallOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_key", promoter.getUserKey());
            queryWrapper.in("status", "using", BaseConstants.ORDER.COMPLETED);
            queryWrapper.orderByDesc("create_time");
            List<MallOrder> mallOrderList = orderService.list(queryWrapper);
            MallOrder mallOrder = null;
            if (mallOrderList.size() > 0) {
                mallOrder = mallOrderList.get(0);
            }

            if (mallOrder != null) {
                MallOrderGoods queryEntity = new MallOrderGoods();
                queryEntity.setOrderKey(mallOrder.getOrderKey());
                queryEntity.setType(1);
                MallOrderGoods orderGoods = baseMallOrderGoodsService.getOneByEntity(queryEntity);
                promoter.setOrderNum(1);
                promoter.setAttrName(orderGoods.getAttrNames());
                promoter.setOriginalPrice(mallOrder.getUseDepositMoney());
                promoter.setOrderStatus(mallOrder.getStatus());
                promoter.setAmount(mallOrder.getAmount());
                promoter.setProductName(orderGoods.getGoodsName());
            }
        }

        return Response.success(statisDTO);
    }

    public String getUserStatu(String userKey) throws RuntimeException {
        Map<String, Object> map = new HashMap<>();
        map.put("userKey", userKey);

        try {
            okhttp3.Response response = HttpClientUtils.get(pluginRentUrlService.getQueryUserStatuURL(), map);
            String str = response.body().string();
            if (!StringUtils.isEmpty(str)) {
                JSONObject jsonObject = JSON.parseObject(str);
                if (jsonObject.getInteger("code") != 200) {
                    throw new RuntimeException(jsonObject.getString("message"));
                }
                return jsonObject.getString("data");
            }
        } catch (Exception e) {
            log.error("用户状态查询异常：" + e);
        }
        return "";
    }
}
